package vn.pyco.prez.tapestry.tasks;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.poi.hslf.model.Comment;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import vn.pyco.prez.dao.DaoManager;
import vn.pyco.prez.model.Slide;
import vn.pyco.prez.model.impl.SlideImpl;

public class ConvertPptTask extends ConvertionTask {
	
	private static final Logger logger = LoggerFactory.getLogger(ConvertPptTask.class); 
	
	private SlideShow _ppt;
	
	public ConvertPptTask(File ppt, DaoManager<List<Slide>> slideManager) {
		super(ppt, slideManager);
		try {
			_ppt = new SlideShow(new FileInputStream(getFileToConvert()));
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
			throw new IllegalArgumentException("The File " + ppt.getName() + " is not a PPT file.");
		}
	}

	
	
	@Override
	public void run() {
		int slidenum = -1;
		float scale = 1;
		
		File tmp = new File(System.getProperty("java.io.tmpdir") + File.separator + getId() + File.separator );
		tmp.mkdir();
		
		Dimension pgsize = _ppt.getPageSize();
        int width = (int) (pgsize.width * scale);
        int height = (int) (pgsize.height * scale);
        
		// convert each slide into a .png file
        org.apache.poi.hslf.model.Slide[] slide = _ppt.getSlides();
        
        //Init Progress
        setProgress(0);
        for (int i = 0; i < slide.length; i++) {
            if (slidenum != -1 && slidenum != (i + 1)) continue;
            String title = slide[i].getTitle();
            Comment[] notes = slide[i].getComments();

            logger.info("Rendering slide " + (i + 1) + (title == null ? "" : ": " + title));

            BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = img.createGraphics();

            // default rendering options
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);

            graphics.setColor(Color.white);
            graphics.clearRect(0, 0, width, height);

            graphics.scale(scale, scale);

            // draw stuff
            slide[i].draw(graphics);

            // save the result
            DecimalFormat df = new DecimalFormat("000");
            String fname = tmp.getAbsolutePath() + File.separator + df.format(Double.parseDouble(Integer.toString(i))) + "-ConvertedSlide.png";
            File output = new File(fname);
            FileOutputStream outputStream;

            try {
				logger.info("Saving image : " + fname);
				outputStream = new FileOutputStream(fname);
				ImageIO.write(img, "png", outputStream);
				outputStream.close();
				Slide s = new SlideImpl(output, notes == null ? "" : extractText(notes, false), title == null ? "No Title" : title, output.getName());
				getSlides().add(s);
			} catch (IOException e) {
				logger.error(e.getMessage(),e);
				throw new IllegalArgumentException("Path " + fname + "is invalid");
			}
            //Update Progress
            setProgress(((double)i+1)/(double)slide.length*100);
        }
        setProgress(100);
        getSlideManager().save(getId(), getSlides());
        logger.info("Convertion finished");
	}
	

    private String extractText(Comment[] data, boolean skipPlaceholders) {
    	StringBuffer text = new StringBuffer();
    	for (int i = 0; i < data.length; i++) {
			Comment c = data[i];
			text.append(c.getText() +"\n");
		}
        return text.toString();
     }	

}
